<template>
  <div>
    <el-button type="primary" @click="handleAdd">新增角色</el-button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="角色ID">
        <template #default="scope">
          {{ scope.row.objectId }}
        </template>
      </el-table-column>
      <el-table-column label="角色名称">
        <template #default="scope">
          {{ scope.row.roleName }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-drawer v-model="drawer" title="录入角色">
      <RoleForm
        v-if="drawer"
        @trans-role-data="addRole"
        :idx="editIdx"
        :row="rowData"
      />
    </el-drawer>
  </div>
</template>

<script>
import { roleGet, roleDel } from "../../api/user";
import RoleForm from "./components/role-form.vue";
import { ElMessageBox } from "element-plus";
export default {
  components: {
    RoleForm,
  },
  data() {
    return {
      tableData: [],
      drawer: false,
      editIdx: -1, //区分新增、编辑
      rowData: null, //被编辑的数据包
    };
  },
  created() {
    roleGet().then((res) => {
      this.tableData = res.data.results;
    });
  },
  methods: {
    addRole(roleObj) {
      this.tableData.push(roleObj);
      this.drawer = false;
    },
    //修改按钮
    handleEdit(index, row) {
      // console.log(index, row);
      this.drawer = true;
      this.editIdx = index;
      this.rowData = row;
      console.log("rowData", row);
    },
    handleDelete(index, row) {
      console.log(index, row);
      ElMessageBox.confirm("删除后数据无法找回", "确定要删除吗？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        console.log("点了确定");
        roleDel(row.objectId).then((res) => {
          this.tableData.splice(index, 1);
        });
        // ElMessage({
        //   type: "success",
        //   message: "Delete completed",
        // });
      });
    },
    //新增按钮
    handleAdd() {
      this.drawer = true;
      this.editIdx = -1;
      this.rowData = null;
    },
  },
};
</script>
